﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace JTT.Dev.Toolkit
{
    /// <summary>
    /// JSON
    /// </summary>
    namespace JSON
    {
        /// <summary>
        /// JSON辅助类
        /// </summary>
        public static class JSONHelper
        {
            /// <summary>
            /// JSON序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="_Object"></param>
            /// <returns></returns>
            public static String ObjectToJson<T>(this T _Object)
            {
                using (MemoryStream TempMemoryStream = new MemoryStream())
                {
                    String MySerializationString = String.Empty;
                    DataContractJsonSerializer MyDataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
                    MyDataContractJsonSerializer.WriteObject(TempMemoryStream, _Object);
                    MySerializationString = Encoding.UTF8.GetString(TempMemoryStream.ToArray());
                    return MySerializationString;
                }

            }

            /// <summary>
            /// JSON反序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="_JsonString"></param>
            /// <returns></returns>
            public static T JsonToObject<T>(this String _JsonString)
            {
                using (MemoryStream TempMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_JsonString)))
                {
                    DataContractJsonSerializer MyDataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
                    return (T)MyDataContractJsonSerializer.ReadObject(TempMemoryStream);
                }
            }

            /// <summary>
            /// JSON序列化（Newtonsoft版本）
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="_Object"></param>
            /// <returns></returns>
            public static String ObjectToJson2(this Object _Object)
            {
                return JsonConvert.SerializeObject(_Object);
            }
        }
    }
}
